package
{
	import com.gk.util.component.Label;
	import com.gk.util.component.ProgressBar;
	
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.ProgressEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.text.TextFormat;

	[SWF(width="760", height="600", frameRate="24")]
	public class Loading extends Sprite
	{
		private var progressBar:ProgressBar;

		private var gameloader:Loader;
		private var config:XML;

		private var configLoader:URLLoader;
		public function Loading()
		{
			if(stage){
				init();
			}else{
				addEventListener(Event.ADDED_TO_STAGE,init);
			}
		}
		private function init(e:Event = null):void{
			if(e) removeEventListener(Event.ADDED_TO_STAGE,init);
			stage.scaleMode = StageScaleMode.NO_SCALE;
			stage.align = StageAlign.TOP_LEFT;
			progressBar = new ProgressBar(this,0,0);
			progressBar.move(stage.stageWidth/2-progressBar.width/2,stage.stageHeight/2-progressBar.height/2);
			
			var label:Label = new Label(this,0,0,"游戏王国");
			label.textField.defaultTextFormat =new TextFormat("Microsoft YaHei",24);
			label.draw();
			label.move(stage.stageWidth/2-label.width/2,stage.stageHeight/2-label.height/2-50);
			
			configLoader = new URLLoader();
			configLoader.addEventListener(Event.COMPLETE,loadConfigHandler);
			configLoader.load(new URLRequest("config.xml"));
		}
		/**
		 *加载配置 
		 * @param e
		 * 
		 */		
		private function loadConfigHandler(e:Event):void
		{
			this.config = XML(e.currentTarget.data);
			configLoader.removeEventListener(Event.COMPLETE,loadConfigHandler);
			loadMain();
		}
		/**
		 *加载主程序 
		 * 
		 */		
		private function loadMain():void{
			gameloader = new Loader();
			gameloader.contentLoaderInfo.addEventListener(Event.COMPLETE,loadMainComHandler);
			gameloader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,progressHandler);
			gameloader.load(new URLRequest(String(this.config.mainSWF)));
		}
		
		private function progressHandler(e:ProgressEvent):void
		{
			progressBar.value = Math.round(progressBar.maximum * (e.bytesLoaded / e.bytesTotal));
		}
		
		private function loadMainComHandler(e:Event):void
		{
			var GameKingClass:Class = gameloader.contentLoaderInfo.applicationDomain.
				getDefinition("GameKing") as Class;
			var game:* = new GameKingClass();
			game.setConfig(this.config);
			
			while(this.numChildren>0){
				this.removeChildAt(0);
			}
			
			addChild(game);
			
			gameloader.contentLoaderInfo.removeEventListener(Event.COMPLETE,loadMainComHandler);
			gameloader.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS,progressHandler);
		}
	}
}